﻿using System;
using System.Data;
using System.Windows.Forms;
using Company.BLL;
using Company.BLL.KDT.GC;
using Company.BLL.DuLieuChuan;
using Janus.Windows.GridEX;
using Company.BLL.KDT;

namespace Company.Interface.KDT.GC
{
	public partial class ToKhaiGCCTManagerForm : BaseForm
	{
        private ToKhaiChuyenTiepCollection tkctCollection = new ToKhaiChuyenTiepCollection();

        public ToKhaiGCCTManagerForm()
		{
			InitializeComponent();
		}

		//-----------------------------------------------------------------------------------------
		
	    private void khoitao_DuLieuChuan()
	    {
	        //string where = string.Format("[ID] LIKE '{0}'", GlobalSettings.MA_CUC_HAI_QUAN);
            this._DonViHaiQuan = DonViHaiQuan.SelectAll();
            this._DonViTinh = DonViTinh.SelectAll();
	    }
	    
	    private void loadData()
		{
            string where = string.Format("TrangThai = {0} OR TrangThai = {1}", Convert.ToInt32(TrangThaiXuLy.CHO_DUYET), Convert.ToInt32(TrangThaiXuLy.DA_DUYET));
            this.tkctCollection = new ToKhaiChuyenTiep().SelectCollectionDynamic(where, "");
            foreach (ToKhaiChuyenTiep tkct in this.tkctCollection)
			{
				DataRow dr = dtToKhaiMauDich.NewRow();
				dr["tkct_Id"] = tkct.ID;
				dr["loaihinh_Ten"] = tkct.TenLoaiHinh;
                dr["tkct_SoTiepNhan"] = tkct.SoTiepNhan;
				dr["haiquan_Ten"] = this.DonViHaiQuan_GetName(tkct.MaHQ);
                dr["tkct_NgayTiepNhan"] = tkct.NgayTiepNhan;
                dr["tkct_NgayDangKy"] = tkct.NgayDangKy;
                if (tkct.TrangThai == TrangThaiXuLy.CHO_DUYET)
                {
                    dr["TTXL_Ten"] = "Chờ duyệt";
                }
                else if (tkct.TrangThai == TrangThaiXuLy.DA_DUYET)
                {
                    dr["TTXL_Ten"] = "Đã duyệt";
                }
			    
                dtToKhaiMauDich.Rows.Add(dr);
				tkct.LoadHCTCollection();
			    //
                foreach (HangChuyenTiep hct in tkct.HCTCollection)
				{
					DataRow row = dtHangMauDich.NewRow();
                    row["hct_MaPhu"] = hct.MaHang;
                    row["hct_TenHang"] = hct.TenHang;
                    row["hct_MaHS"] = hct.MaHS;
                    row["donvitinh_Ten"] = this.DonViTinh_GetName(hct.ID_DVT);
                    row["hct_STTHang"] = hct.SoThuTuHang;
                    row["SoLuong"] = hct.SoLuong;
					row["tkct_Id"] = tkct.ID;
					dtHangMauDich.Rows.Add(row);
				}
			}
		}

        private void ToKhaiGCCTManagerForm_Load(object sender, EventArgs e)
		{
            this.Cursor = Cursors.WaitCursor;
            this.khoitao_DuLieuChuan();
            cbStatus.SelectedIndex = 0;
		    this.search();

		    try
			{
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			finally
			{
				this.Cursor = Cursors.Default;
			}
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnGetListFromHQ_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this.tkctCollection.Count == 0) return;
                WSForm wsForm = new WSForm();
                wsForm.ShowDialog(this);
                if (!wsForm.IsReady) return;
                string strSTN = "";
                foreach (ToKhaiChuyenTiep tkct in this.tkctCollection)
                {
                    try
                    {
                        int ttxl = tkct.TrangThai;
                        tkct.WSRequestStatus();
                        if (ttxl < tkct.TrangThai)
                        {
                            if (strSTN == "") strSTN += tkct.SoTiepNhan;
                            else strSTN += ", " + tkct.SoTiepNhan.ToString();
                        }
                    }
                    catch
                    {
                        HangDoi hd = new HangDoi();
                        hd.ID = tkct.ID;
                        hd.LoaiToKhai = LoaiToKhai.TO_KHAI_MAU_DICH;
                        hd.TrangThai = tkct.TrangThai;
                        hd.ChucNang = ChucNang.KHAI_BAO;
                        MainForm.AddToQueueForm(hd);
                        MainForm.ShowQueueForm();
                    }
                }
                if (strSTN != "")
                    ShowMessage("Đồng bộ dữ liệu thành công.\nTrạng thái của các tờ khai có số tiếp nhận: " + strSTN + " đã thay đổi thành 'đã duyệt chính thức'.", false);
                else
                    ShowMessage("Đồng bộ dữ liệu thành công.", false);
                this.search();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message, false);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private ToKhaiChuyenTiep getTKCTByID(long id)
        {
            foreach (ToKhaiChuyenTiep tk in this.tkctCollection)
            {
                if (tk.ID == id) return tk;
            }
            return null;
        }
        private void dgList_RowDoubleClick(object sender, Janus.Windows.GridEX.RowActionEventArgs e)
        {
            if (e.Row.Children != 0 && e.Row.RowType == RowType.Record)
            {
                if (e.Row.Cells["TTXL_Ten"].Text == "Chờ duyệt" || e.Row.Cells["TTXL_Ten"].Text == "Chưa khai báo")
                {
                    long id = Convert.ToInt64(e.Row.Cells["tkct_Id"].Value);
                    ToKhaiGCChuyenTiepNhapForm f = new ToKhaiGCChuyenTiepNhapForm();
                    f.OpenType = OpenFormType.Edit;
                    f.TKCT = this.getTKCTByID(id);
                    f.ShowDialog();
                }
                else 
                {
                    long id = Convert.ToInt64(e.Row.Cells["tkct_Id"].Value);
                    ToKhaiGCChuyenTiepNhapForm f = new ToKhaiGCChuyenTiepNhapForm();
                    f.OpenType = OpenFormType.View;
                    f.TKCT = this.getTKCTByID(id);
                    f.ShowDialog();
                }
            }
        }
        private void search()
        {
            // Xây dựng điều kiện tìm kiếm.
            string where = "1 = 1";
            where += string.Format(" AND MaHQ = '{0}'", ctrDonViHaiQuan.Ma);

            if (txtSoTiepNhan.TextLength > 0)
            {
                where += " AND SoTiepNhan = " + txtSoTiepNhan.Value;
            }

            if (Convert.ToInt32(cbStatus.SelectedValue) != TrangThaiXuLy.CHUA_KHAI_BAO)
            {
                if (txtNamTiepNhan.TextLength > 0)
                {
                    where += " AND YEAR(NgayTiepNhan) = " + txtNamTiepNhan.Value;
                }
            }
            if(cbStatus.SelectedValue!=null)
                where += " AND TrangThai = " + cbStatus.SelectedValue;

            // Thực hiện tìm kiếm.            
            this.tkctCollection = new ToKhaiChuyenTiep().SelectCollectionDynamic(where, "");
            dtHangMauDich.Rows.Clear();
            dtToKhaiMauDich.Rows.Clear();
            
            foreach (ToKhaiChuyenTiep tkct in this.tkctCollection)
            {
                DataRow dr = dtToKhaiMauDich.NewRow();
                dr["tkct_Id"] = tkct.ID;
                dr["loaihinh_Ten"] = tkct.TenLoaiHinh;
                dr["tkct_SoTiepNhan"] = tkct.SoTiepNhan;
                dr["haiquan_Ten"] = this.DonViHaiQuan_GetName(tkct.MaHQ);
                dr["tkct_NgayTiepNhan"] = tkct.NgayTiepNhan;
                dr["tkct_NgayDangKy"] = tkct.NgayDangKy;
                if (tkct.TrangThai == TrangThaiXuLy.CHO_DUYET)
                {
                    dr["TTXL_Ten"] = "Chờ duyệt";
                }
                else if (tkct.TrangThai == TrangThaiXuLy.DA_DUYET)
                {
                    dr["TTXL_Ten"] = "Đã duyệt";
                }
                else if (tkct.TrangThai == TrangThaiXuLy.CHUA_KHAI_BAO)
                {
                    dr["TTXL_Ten"] = "Chưa khai báo";
                }
                dtToKhaiMauDich.Rows.Add(dr);
                tkct.LoadHCTCollection();
                //
                foreach (HangChuyenTiep hct in tkct.HCTCollection)
                {
                    DataRow row = dtHangMauDich.NewRow();
                    row["hct_MaPhu"] = hct.MaHang;
                    row["hct_TenHang"] = hct.TenHang;
                    row["hct_MaHS"] = hct.MaHS;
                    row["donvitinh_Ten"] = this.DonViTinh_GetName(hct.ID_DVT);
                    row["hct_STTHang"] = hct.SoThuTuHang;
                    row["SoLuong"] = hct.SoLuong;
                    row["tkct_Id"] = tkct.ID;
                    dtHangMauDich.Rows.Add(row);
                }
            }

            this.setCommandStatus();

            //this.currentNPLDangKy.TrangThaiXuLy = Convert.ToInt32(cbStatus.SelectedValue);
        }

        private void setCommandStatus()
        {
            switch (Convert.ToInt32(cbStatus.SelectedValue))
            {
                case -1:
                    cmdSend.Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    cmdCancel.Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    cmdSingleDownload.Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    btnGetListFromHQ.Enabled = false;
                    break;
                case 0:
                    cmdSend.Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    cmdCancel.Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    cmdSingleDownload.Enabled = Janus.Windows.UI.InheritableBoolean.True;
                    btnGetListFromHQ.Enabled = true;
                    break;
                case 1:
                    cmdSend.Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    cmdCancel.Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    cmdSingleDownload.Enabled = Janus.Windows.UI.InheritableBoolean.False;
                    btnGetListFromHQ.Enabled = false;
                    break;
            }
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.search();
        }

        private void cmMain_CommandClick(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
        {
            switch (e.Command.Key)
            {
                case "cmdSend":
                    Send();
                    break;
                case "cmdSingleDownload":
                    Download();
                    break;
                case "cmdCancel":
                    Cancel();
                    break;
             }
        }

        private void Cancel()
        {
            ToKhaiChuyenTiep tkct = new ToKhaiChuyenTiep();
            try
            {
                if (dgList.GetRow() != null && dgList.GetRow().RowType==RowType.Record && dgList.GetRow().Children>0)
                {
                    this.Cursor = Cursors.WaitCursor;
                    WSForm wsForm = new WSForm();
                    wsForm.ShowDialog(this);
                    if (!wsForm.IsReady) return;

                    tkct = this.search(dgList.GetRow().Cells["tkct_id"].Value);
                    long soTiepNhan = tkct.SoTiepNhan;
                    
                    if (tkct.WSCancel())
                    {
                        ShowMessage("Hủy khai báo tờ khai chuyển tiếp có số tiếp nhận " + soTiepNhan + " thành công", false);

                    }
                    else
                    {
                        ShowMessage("Hủy khai báo tờ khai chuyển tiếp không thành công.", false);
                    }

                    this.search();
                }
            }
            catch (Exception ex)
            {
                if (ShowMessage("Hủy khai báo không thành công.\nLỗi: " + ex.Message + "\nBạn có muốn đưa vào hàng đợi không?", true) == "Yes")
                {
                    HangDoi hd = new HangDoi();
                    hd.ID = tkct.ID;
                    hd.LoaiToKhai = LoaiToKhai.TO_KHAI_CHUYEN_TIEP;
                    hd.TrangThai = tkct.TrangThai;
                    hd.ChucNang = ChucNang.HUY_KHAI_BAO;
                    MainForm.AddToQueueForm(hd);
                    MainForm.ShowQueueForm();

                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private ToKhaiChuyenTiep search(object id)
        {
            foreach (ToKhaiChuyenTiep tkct in this.tkctCollection)
            {
                if (tkct.ID == Convert.ToInt64(id))
                {
                    return tkct;
                }
            }
            return null;
        }
        private void Download()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                GridEXSelectedItemCollection items = dgList.SelectedItems;
                foreach (GridEXSelectedItem i in items)
                {
                    if (i.GetRow().Children > 0)
                    {
                        if (i.RowType == RowType.Record)
                        {
                            ToKhaiChuyenTiep tkct = this.search(i.GetRow().Cells["tkct_id"].Value);

                            int ttxl = tkct.TrangThai;

                            WSForm wsForm = new WSForm();
                            wsForm.ShowDialog(this);
                            if (!wsForm.IsReady) return;
                            try
                            {
                                tkct.WSRequestStatus();

                                if (ttxl < tkct.TrangThai)
                                {
                                    ShowMessage("Nhận dữ liệu thành công! \nTrạng thái chứng từ đã thay đổi: Đã duyệt chính thức.", false);
                                    this.search();
                                }
                                else if (ttxl == tkct.TrangThai)
                                {
                                    ShowMessage("Nhận dữ liệu thành công!", false);
                                    dgList.Refetch();
                                }
                            }
                            catch
                            {
                                if (ShowMessage("Nhận dữ liệu không thành công.\nBạn có muốn đưa vào hàng đợi không?", true) == "Yes")
                                {
                                    HangDoi hd = new HangDoi();
                                    hd.ID = tkct.ID;
                                    hd.LoaiToKhai = LoaiToKhai.TO_KHAI_CHUYEN_TIEP;
                                    hd.TrangThai = tkct.TrangThai;
                                    hd.ChucNang = ChucNang.NHAN_THONG_TIN;
                                    MainForm.AddToQueueForm(hd);
                                    MainForm.ShowQueueForm();

                                }
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message,false);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void Send()
        {
            ToKhaiChuyenTiep tkct = new ToKhaiChuyenTiep();
            try
            {
                if (dgList.GetRow() != null && dgList.GetRow().RowType == RowType.Record && dgList.GetRow().Children > 0)
                {
                    this.Cursor = Cursors.WaitCursor;
                    WSForm wsForm = new WSForm();
                    wsForm.ShowDialog(this);
                    if (!wsForm.IsReady) return;
                    
                    tkct = this.search(dgList.GetRow().Cells["tkct_id"].Value);
                    long soTiepNhan = tkct.WSSend();
                    if (soTiepNhan > 0)
                    {
                        ShowMessage("Khai báo tờ khai chuyển tiếp thành công.\nSố tiếp nhận: " + soTiepNhan, false);

                    }
                    else
                    {
                        ShowMessage("Khai báo tờ khai chuyển tiếp không thành công.", false);
                    }

                    this.search();
                }
            }
            catch (Exception ex)
            {
                if (ShowMessage("Khai báo không thành công.\nLỗi: " + ex.Message + "\nBạn có muốn đưa vào hàng đợi không?", true) == "Yes")
                {
                    HangDoi hd = new HangDoi();
                    hd.ID = tkct.ID;
                    hd.LoaiToKhai = LoaiToKhai.TO_KHAI_CHUYEN_TIEP;
                    hd.TrangThai = tkct.TrangThai;
                    hd.ChucNang = ChucNang.KHAI_BAO;
                    MainForm.AddToQueueForm(hd);
                    MainForm.ShowQueueForm();

                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void cmMain_CommandClick_1(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
        {
            switch (e.Command.Key)
            {
                case "cmdSend":
                    Send();
                    break;
                case "cmdSingleDownload":
                    Download();
                    break;
                case "cmdCancel":
                    Cancel();
                    break;
            }
        }

        private void dgList_DeletingRecord(object sender, RowActionCancelEventArgs e)
        {
            if (e.Row.Children > 0)
            {
                if (e.Row.RowType == RowType.Record)
                {
                    ToKhaiChuyenTiep tkct = (ToKhaiChuyenTiep)e.Row.DataRow;
                    if (tkct.TrangThai == TrangThaiXuLy.CHUA_KHAI_BAO)
                    {
                        if (ShowMessage("Bạn có muốn xóa tờ khai chuyển tiếp này không?", true) == "Yes")
                        {
                            tkct.Delete();
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                    }

                    
                }
            }
        }

	}
}